package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;


    @Autowired
    ArticleFeign articleFeign;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        // 1. 校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        // 2. 查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user==null?null:user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"获取行为实体信息失败");
        }
        // 3. 查询指定文章阅读行为是否存在
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        if(readBehavior == null){
            // 不存在    新增阅读行为
            readBehavior = new ApReadBehavior();
            readBehavior.setEntryId(apBehaviorEntry.getId());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount((short)1);
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(readBehavior);
        }else {
            // 存在     更新阅读次数
            readBehavior.setCount((short)(readBehavior.getCount() + 1));
            mongoTemplate.save(readBehavior);
        }
        //根据文章id查询文章作者id
        ResponseResult<Long> result = articleFeign.findAuthorById(dto.getArticleId());
        if(!result.checkCode()){
            log.error("远程调用 articleFeign.findAuthorById出错");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用 articleFeign.findAuthorById错误");
        }
        Long authorId = result.getData();
        log.info("作者id为 {}",authorId );

        //查询redis中的zet  判断是否关注过读者
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        Double score = zSetOperations.score(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(authorId));
        log.info("分数为 {}" ,score);
        if (score == null){
            UpdateArticleMess mess = new UpdateArticleMess();
            mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
            mess.setArticleId(dto.getArticleId());
            mess.setAdd(1);
            rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
            log.info("阅读行为 发送消息 ==>{}",mess);
        }else{
            UpdateArticleMess mess = new UpdateArticleMess();
            mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
            mess.setArticleId(dto.getArticleId());
            mess.setAdd(1);
            rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
            log.info("阅读行为 发送消息 ==>{}",mess);
            UpdateArticleMess mess2 = new UpdateArticleMess();
            mess2.setType(UpdateArticleMess.UpdateArticleType.FANS_VIEWS);
            mess2.setArticleId(dto.getArticleId());
            mess2.setAdd(1);
            rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess2));
            log.info("粉丝阅读行为 发送消息 ==>{}",mess2);
        }

        return ResponseResult.okResult();
    }
}
